package com.paddyi.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.paddyi.mapper.OrganizationMapper;
import com.paddyi.model.Organization;
import com.paddyi.service.IOrganizationService;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

/**
 * 组织机构 (Organization)
 *
 * @author paddy
 * @since 2019-04-26 04:34:10
 */
@Service
public class OrganizationServiceImpl extends ServiceImpl<OrganizationMapper, Organization> implements IOrganizationService {


    @Override
    public List<Organization> findTree() {

        List<Organization> resources = this.list();
        List<Organization> resourceVos = new ArrayList<>();
        for(Organization resource:resources){
            if(resource.getPid() == 0 ){
                resourceVos.add(resource);
                children(resource,resources);
            }
        }
        resourceVos.sort(Comparator.comparing(Organization::getSeq));

        return resourceVos;
    }

    private void children (Organization resource,List<Organization> resources){
        List<Organization> childrens = new ArrayList<>();
        for(Organization re:resources){
            if(re.getPid() !=null && resource.getId().longValue() == re.getPid().longValue()){
                re.setParentName(resource.getName());
                childrens.add(re);
                children(re, resources);
            }
        }
        childrens.sort(Comparator.comparing(Organization::getSeq));
        resource.setChildren(childrens);

    }
}
